#include "StdAfx.h"
#include "SoundPlayer.h"

SoundPlayer::SoundPlayer(void)
{
	lastSample = 0;
}

SoundPlayer::~SoundPlayer(void)
{
	if(lastSample)
	{
		delete lastSample;
	}
}

void SoundPlayer::Initialize(unsigned int ChannelsCount, unsigned int SampleRate)
{
	sf::SoundStream::Initialize(ChannelsCount, SampleRate);
}

bool SoundPlayer::HasMoreSamples()
{
	return buffer.size()>0;
}

bool SoundPlayer::OnGetData(Chunk& Data)
{
	if(lastSample)
	{
		delete lastSample;
		lastSample = 0;
	}

	while(buffer.size()==0)
	{
		Sleep(5);
	}


	mutex.Lock();
	int length = buffer.size();
	lastSample = new short[length];
	for(int i=0; i<length; i++) 
	{
		short cur = buffer.front();
		buffer.pop();
		lastSample[i] = cur;
	}
	mutex.Unlock();
	Data.Samples = lastSample;
	Data.NbSamples = length;
	return true;
}

void SoundPlayer::NewSample(short* sample, int length)
{
	mutex.Lock();
	for(int i=0; i<length; i++)
	{
		buffer.push(sample[i]);
	}
	mutex.Unlock();
}